/*
    Copyright 2006 Andrew Wilkinson <andrew@indiegigs.co.uk>

    This file is part of libgp2x.

    libgp2x is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    libgp2x is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with libgp2x; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include <string.h>
#include <stdlib.h>
#include <tremor/ivorbisfile.h>

#include "gp2x_940t.h"

#include "messages.h"

entry_point

size_t read_func(void* ptr, size_t size, size_t nmemb, void* datasource) {
    memfile* mf = (memfile*)datasource;
    if(mf->pos + size*nmemb > mf->size) {
        nmemb = nmemb / (mf->size - mf->pos);
    }
    memcpy(ptr, GP2x_convert_ptr_from(mf->ptr) + mf->pos, size*nmemb);
    mf->ptr += mf->pos + size*nmemb;
    return size*nmemb;
}

int seek_func(void* datasource, ogg_int64_t offset, int whence) {
    memfile* mf = (memfile*)datasource;
    switch(whence) {
    case SEEK_SET:
        mf->pos = offset;
        break;
    case SEEK_CUR:
        mf->pos += offset;
        break;
    case SEEK_END:
        mf->pos = mf->size;
        break;
    }
    return mf->pos;
}

int close_func(void* datasource) {
    free(GP2x_convert_ptr_from(((memfile*)datasource)->ptr));
    free(datasource);
    return 1;
}

long tell_func(void* datasource) {
    return ((memfile*)datasource)->pos;
}

int main() {
    unsigned long message;
    unsigned long value;
    ov_callbacks callbacks;
    OggVorbis_File vf;

    callbacks.read_func = read_func;
    callbacks.seek_func = seek_func;
    callbacks.close_func = close_func;
    callbacks.tell_func = tell_func;

    while(1) {
        GP2x_wait_message(&message, &value);
        if(message == PLAY) {
            printf("Pointer: %p\n", (void*)GP2x_convert_ptr_from(value));
            ov_open_callbacks((void*)GP2x_convert_ptr_from(value), &vf, NULL, 0, callbacks);
        }
    }

    return 0;
}
